import json
import sys
import time
import traceback

import requests

from category.videospecstocknews import NewsGenerateVideo
from config import *

def fetch_upload_videos():
    print("start fetch upload videos")
    # api_host = "http://127.0.0.1:8083"
    api_host = "http://jfj8.bjyihuilian.com"
    try:
        response = requests.get(api_host + '/v1/pic/get_news_scripts_by_status/7')
    except Exception as e:
        traceback.print_exc()
        print("拉取待处理的异动新闻数据异常")
        return 0
    list = json.loads(response.text)
    # print(APP_ROOT + os.sep + 'temp' + os.sep + '5' + os.sep + 'out.mp4')
    print(list)

    # return 0;

    success_count = 0
    for item in list:
        res_id = str(item['id'])
        # res_id = '5ef177466bc1c7ebcf62d979'
        try:
            generator = NewsGenerateVideo(res_id=res_id, ppt_tpl_path='', api_host=api_host)
            # 同步至服务器
            generator.generate_result['video_path'] = APP_ROOT + os.sep + 'temp' + os.sep + res_id + os.sep + 'out.mp4' # print('上传：：：' + res_id + "@" + generator.generate_result['video_path'])
            generator.sync_result_to_server()
            print('upload..end..')
            success_count = success_count + 1
        except Exception as e:
            traceback.print_exc()
            print("生成异动股票失败 res_id :{}".format(res_id))
    return success_count

def fetch_generating_videos():
    print("start fetch generating videos")
    # api_host = "http://127.0.0.1:8083"
    api_host = "http://jfj8.bjyihuilian.com"
    try:
        response = requests.get(api_host + '/v1/pic/get_news_scripts_by_status/5')
    except Exception as e:
        traceback.print_exc()
        print("拉取待处理的异动新闻数据异常")
        return 0
    list = json.loads(response.text)
    # print(list)

    success_count = 0
    for item in list:
        res_id = str(item['id'])
        # res_id = '5ef177466bc1c7ebcf62d979'
        try:
            generator = NewsGenerateVideo(res_id=res_id, ppt_tpl_path=TEMPLATE_PATH + 'spec_news_stock.pptx',
                                          api_host=api_host)
            # 1.加载脚本数据
            generator.fetch_script_data()
            # 2.生成数据
            generator.generate()
            # 3.同步至服务器
            # generator.sync_result_to_server()
            success_count = success_count + 1
        except Exception as e:
            traceback.print_exc()
            print("生成异动股票失败 res_id :{}".format(res_id))
    return success_count

def start_job2():
    no_data_count = 0
    while True:
        count = fetch_generating_videos()
        fetch_upload_videos()
        count = 0
        if count == 0:
            no_data_count = no_data_count + 1
        else:
            no_data_count = 0

        if no_data_count != 0:
            time.sleep(min(no_data_count * 5, 30))


if __name__ == '__main__':
    start_job2()
